import { Injectable, UnauthorizedException } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { ExtractJwt, Strategy } from 'passport-jwt';
import { ConfigService } from '@nestjs/config';
import { AuthService } from '../auth.service';

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
    constructor(
        private configService: ConfigService,
        private authService: AuthService,
    ) {
        super({
            jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
            ignoreExpiration: false,
            secretOrKey: configService.get<string>('JWT_SECRET') || 'ai-painting-platform-secret',
        });
    }

    async validate(payload: any) {
        try {
            const user = await this.authService.validateUser(payload.sub);
            return {
                userId: payload.sub,
                username: payload.username,
                roles: payload.roles,
            };
        } catch (error) {
            throw new UnauthorizedException('无效的认证信息');
        }
    }
} 